const { getErr } = require('./util')
const { pathToRegexp } = require('path-to-regexp')
const crypt = require('./crypt')

// 需要认证的api集合
const needTokenApi = [
    { method: "GET", path: '/api/info' },
    { method: "PUT", path: '/api/info/:id' }
]

// 用于解析token
// 验证token是否通过
module.exports = (req, res, next) => {

    // api是否需要认证
    const apis = needTokenApi.filter(({ method, path }) => {
        // 通过 path-to-regexp 库 api/info/:id 匹配 api/info/177
        const reg = pathToRegexp(path)
        return method == req.method && reg.test(req.path)
    })
    console.log('token', req.session);
    if (!apis.length) return next();

    if (req.sessio.loginUser) {
        // 已经登录过了
        next()
    } else {
        handleNoToken(req, res, next)
    }

}
// 处理没有认证的情况
function handleNoToken(req, res, next) {
    res.status(403).send(getErr('token验证失败', 403))
}